 #include "daemon_sub_process.h"

/**
 * @brief 子进程的初始化
 */
daemon_sub_process_t *daemon_sub_process_init(char *sub_arg)
{
    daemon_sub_process_t *sub_process = malloc(sizeof(daemon_sub_process_t));
    sub_process->sub_arg = sub_arg; //app  ota ...
    sub_process->pid=-1;
    sub_process->fail_count=0;

    return sub_process;

}


/**
 * @brief 对子进程的检查和启动
 */
void daemon_sub_process_check_and_start(daemon_sub_process_t *sub_process)
{
     int over_status =0;
     if( sub_process->pid > 0 &&  waitpid(sub_process->pid,&over_status, WNOHANG)==0 )  //如果正常 则直接返回
     {
        return;
     }
     // 程序没启动  或  程序已经挂了
     if(over_status>0)
     {
         sub_process->fail_count++;
         if(sub_process->fail_count > 5)
         {
             printf("子进程已经启动失败了5次了,请检查子进程是否正常启动\n");
             reboot(RB_AUTOBOOT);
         }
     }
     sub_process->pid = fork();
     if(sub_process->pid == 0)  //子进程启动自己相关业务程序
     {
        //gateway xxx 
        char *cmd=GATEWAY_CMD;
        char *args[3]={cmd,sub_process->sub_arg,NULL};
        char *env[1]={NULL};

        int ret= execve( cmd,args,env);
        if(ret == -1)
        {
            perror("execve");
            _exit(EXIT_FAILURE);
        }

     }




}


/**
 * @brief 销毁子进程
 */
void daemon_sub_process_destroy(daemon_sub_process_t *sub_process)
{
    // 结束进程
    kill(sub_process->pid,SIGTERM);
    waitpid(sub_process->pid,NULL,0);

    free(sub_process);
}